package com.tongna.util;

import com.mchange.v2.c3p0.ComboPooledDataSource;
import com.mchange.v2.c3p0.DataSources;
import jodd.io.FileUtil;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
import org.springframework.core.io.support.PropertiesLoaderUtils;
import org.springframework.dao.DataAccessException;
import org.springframework.jdbc.core.JdbcTemplate;

import java.beans.PropertyVetoException;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Properties;

/**
 * usite
 *
 * @author 张浩伟
 * @version 1.01 2018年02月06日
 */
public class DBUtils {

    private static Logger log = LoggerFactory.getLogger(DBUtils.class);

    public static ComboPooledDataSource createDateSource(String databasesName, String username, String password){
        ComboPooledDataSource defaultDataSource = new ComboPooledDataSource(databasesName);
        Properties properties = loadProperties();
        if (StringUtils.isNotBlank(databasesName)){
            defaultDataSource.setDataSourceName(databasesName);
            defaultDataSource.setJdbcUrl(properties.getProperty("jdbc.url.prefix")
                    + databasesName + properties.getProperty("jdbc.url.suffix"));
        } else {
            defaultDataSource.setDataSourceName(properties.getProperty("jdbc.databaseName"));
            defaultDataSource.setJdbcUrl(properties.getProperty("jdbc.url"));
        }
        if (StringUtils.isNotBlank(username)){
            defaultDataSource.setUser(username);
        } else {
            defaultDataSource.setUser(properties.getProperty("jdbc.username"));
        }
        if (StringUtils.isNotBlank(password)){
            defaultDataSource.setPassword(password);
        } else {
            defaultDataSource.setPassword(properties.getProperty("jdbc.password"));
        }

        defaultDataSource.setInitialPoolSize(16);
        defaultDataSource.setMaxConnectionAge(10000);
        try {
            defaultDataSource.setDriverClass(properties.getProperty("jdbc.driverClassName"));
        } catch (PropertyVetoException e) {
            e.printStackTrace();
        }
        log.info("数据库初始化信息：url={}", defaultDataSource.getJdbcUrl());
        log.info("               ：username={}", defaultDataSource.getUser());
        log.info("               ：password={}", defaultDataSource.getPassword());
        log.info("               ：driverClass={}", defaultDataSource.getDriverClass());
        return defaultDataSource;
    }

    public static Properties loadProperties(){
        try {
            return PropertiesLoaderUtils.loadAllProperties("jdbc.properties");
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    public static boolean createDataBases(String databasesName) {
        try {
            ComboPooledDataSource dateSource = createDateSource(null, null, null);
            JdbcTemplate template = getTemplate(dateSource);
            String sql = "CREATE DATABASE IF NOT EXISTS `"+databasesName+"` DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;";
            template.execute(sql);
            ComboPooledDataSource newDateSource = createDateSource(databasesName, null, null);
            template.setDataSource(newDateSource);
            template.execute("use `" + databasesName +"`");
            template.batchUpdate(loadSql());
            log.info("创建数据库[{}]成功", databasesName);
            return true;
        } catch (DataAccessException e) {
            e.printStackTrace();
        }
        return false;
    }

    private static String[] loadSql(){
        String[] result = new String[0];
        try {
            Resource resource = new ClassPathResource("news.sql");
            File resourceFile = resource.getFile();
            if (resourceFile.canRead()){
                String[] lines = FileUtil.readLines(resourceFile, "UTF-8");
                List<String> sqls = Arrays.asList(lines);
                List<String> tmp = new ArrayList<String>();
                StringBuilder sb = new StringBuilder();
                for (String sql : sqls) {
                    sb.append(sql);
                    if (sb.indexOf(";") != -1){
                        tmp.add(sb.toString());
                        sb.delete(0, sb.length());
                    }
                }
                return tmp.toArray(result);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return result;
    }

    private static JdbcTemplate getTemplate(ComboPooledDataSource dataSource) {
        JdbcTemplate template = new JdbcTemplate();
        template.setDataSource(dataSource);
        return template;
    }

}
